import asyncio
import os
import re
import requests
from pyppeteer import launch
async def main():
    # 启动浏览器
    browser = await launch(executablePath='C:\Program Files\Google\Chrome\Application\chrome.exe')
    page = await browser.newPage()
    # 访问网页
    await page.goto('https://music.163.com/#/discover/toplist')  # 替换为实际的URL
    # 等待iframe加载完成
    await page.waitForSelector('iframe')
    # 获取iframe的frame对象
    frames =page.frames
    iframe_frame = None
    for frame in frames:
        if frame != page.mainFrame:
            iframe_frame = frame
            break
    if iframe_frame:
        # 等待iframe内的内容加载完成
        await iframe_frame.waitForSelector('body')
        # 获取iframe里面的内容
        iframe_content = await iframe_frame.content()
        print("iframe内容:")
        print(iframe_content)
    else:
        print("没有找到iframe的frame对象")
    # 获取歌曲名称
    name_pattren=r'<b title="(.*?)">'
    music_name=re.findall(name_pattren,iframe_content,flags=re.S)
    # 获取歌曲id
    id_patter=r'<span class="txt"><a href="/song\?id=(.*?)"><b'
    music_id=re.findall(id_patter,iframe_content,flags=re.S)
    await browser.close()
    return [music_name,music_id]
# 运行主函数
resp=asyncio.get_event_loop().run_until_complete(main())
music_name_list=resp[0]
music_id_list=resp[1]
for i in range(len(music_name_list)):
    music_url = f'http://music.163.com/song/media/outer/url?id={music_id_list[i]}.mp3'
    hearder={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}
    save_path=r'C:\Users\Administrator\Desktop\网易音乐'
    os.makedirs(save_path,exist_ok=True)
    music_name=music_name_list[i]+'.mp3'
    update_music_name=re.sub(r'[\\/*?:"<>|]','_',music_name)
    save_path1=os.path.join(save_path,update_music_name)
    resp1=requests.get(url=music_url,headers=hearder)
    if resp1.status_code==200:
        with open(save_path1,'wb') as file:
            file.write(resp1.content)
            print('{}音乐保存成功'.format(update_music_name))
    else:
        print('请求音乐接口失败，状态码为：{}'.format(resp1.status_code))
